<template>
	<view>
		<view v-if="vk.vuex.get('$app.appinfo.tips_switch')">
			<!-- 组件说明https://ext.dcloud.net.cn/plugin?id=2435 -->
			<tips :isCustom="true" :text="vk.vuex.get('$app.appinfo.tips_text')||'长按视频画面,拖动可快进'"></tips>
		</view>

		<swiper :style="'width: '+ windowWidth +'px; height: '+ windowHeight +'px; background-color: #000000;'"
			:vertical="true" @animationfinish="animationfinish" @change="change" :current="current"
			:indicator-dots="false" poster-size="fill">
			<swiper-item v-for="(list,index) in dataList" :key="index">
				<view v-if="k==index">
					<video-player v-if="isShow"
						:style="'width: '+ windowWidth +'px; height: '+ videoHeight +'px; background-color: #000000;margin-top:2rpx'"
						@error="error" @getsource="getsource" @ended="ended" :albumId="list.album_id"
						:episodeId="list.episode_id" :cloud-type="1" :version="1" autoplay @play="play()"
						:enable-play-in-background="true" enable-progress-gesture />

					<view v-if="!isShow" @click="click_tvimg(currentInfo)">
						<image :src="tvinfo.tv_image" class="aaaaaimage">
						</image>
					</view>
				</view>
			</swiper-item>
		</swiper>

		<view class="userInfo">
			<!-- 2.点赞 -->

			<view @click="cLike(currentInfo.like);"
				style="opacity: 0.9; margin-top: 17px;display: flex;flex-direction: column;align-items: center;">
				<image v-if="currentInfo.like" src="@/static/xin.png" style="width: 40px; height: 40px;">
				</image>
				<image v-if="!currentInfo.like" src="@/static/xin-2.png" style="width: 40px; height: 40px;">
				</image>

				<view class="xuanjiStyle" :class="{'likeNumActive':currentInfo.like}">
					{{currentInfo.like_num>-1?vk.pubfn.calcSize(currentInfo.like_num, ["","万"], 10000, 1).title:1}}
				</view>
			</view>
			<!-- 3.追剧 -->

			<view @click="follow_tv"
				style="opacity: 0.9; margin-top: 20rpx;display: flex;flex-direction: column;align-items: center;">
				<image v-show="!show_redicon" src="@/static/liaotian-2.png" style="width: 75rpx; height: 75rpx;">
				</image>
				<image v-show="show_redicon" src="@/static/liaotian.png" style="width: 75rpx; height: 75rpx;">
				</image>
				<text class="xuanjiStyle">追剧</text>
			</view>
			<!-- 4.分享 -->

			<view style="opacity: 0.9; margin-top: 30rpx;">
				<view style="opacity: 0;">
					<u-button openType="share" text="分享"></u-button>
				</view>
				<view style="display: flex;flex-direction: column;align-items: center;margin-top: -90rpx;">
					<image src="@/static/wx1.png" style="pointer-events: none;width: 68rpx; height: 68rpx;">
					</image>
					<text class="xuanjiStyle">分享</text>
				</view>

			</view>
			<!-- //选集 -->
			<view style="opacity: 0.9;margin-top: 30rpx;display: flex;flex-direction: column;align-items: center;">
				<image src="@/static/xj.png" style="width: 65rpx;height: 65rpx;" @click="xuanji">
				</image>
				<text @click="xuanji" class="xuanjiStyle">选集</text>
			</view>
		</view>

		<!-- 最底下的文字部分 -->
		<view class="content" v-if="currentInfo.tv_name">
			<view class="userName" :style="'width: '+ (windowWidth - 90) +'px;'">{{currentInfo.title}}</view>
			<view @click="xuanji" class="words" :style="'width: '+ (windowWidth - 40) +'px;'">
				《{{currentInfo.tv_name}}》更新至{{tvinfo.update_witch}}集|选集></view>
		</view>

		<!-- 短剧选集弹窗开始 -->
		<u-popup :show="show" @close="close" @open="open" :round="10" mode="bottom">
			<view class="tv_name">{{tvinfo.tv_name}}</view>
			<view class="update_witch">更新至第 {{total}} 集</view>
			<u-line length="750rpx"></u-line>

			<u-tabs :list="list1" @click="click" :scrollable="true" :current="currentTab"></u-tabs>

			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll">

				<view style="display: flex;flex-direction: row;flex-wrap: wrap;">
					<view v-for="(item,index) in all" :key="index" style="margin: 10rpx;"
						@click="check_series(item,index)">
						<view v-if="item.pay==0||item.had_pay==true||vk.vuex.get('$user.userInfo.plus_type')==1">
							<image class="tv_image" :src="tvinfo.tv_image"></image>
							<view class="series">第 {{item.series}} 集</view>
						</view>
						<view v-if="item.pay>0&&item.had_pay==false&&vk.vuex.get('$user.userInfo.plus_type')==0">
							<image class="tv_image" :src="tvinfo.tv_image"></image>
							<view class="series">第 {{item.series}} 集</view>
							<view class="lock_bg">
								<image class="lock" src="@/static/lock.png"></image>
							</view>
						</view>
					</view>
				</view>
				<u-gap height="30rpx"></u-gap>
			</scroll-view>
		</u-popup>
		<!-- 短剧选集弹窗结束 -->

		<!-- 充值弹窗开始 -->
		<u-popup :show="rechargeShow" @close="rechargeShow = false" @open="rechargeopen" :round="10" mode="bottom"
			customStyle="background-color:rgb(238, 245, 252);">
			<view v-if="vk.vuex.get('$app.osName')=='ios'&&vk.vuex.get('$user.userInfo.invite_code').length<5">
			</view>
			<view v-else>
				<view class="tv_name" @click="zhix">我的余额：{{vk.vuex.get('$user.userInfo.balance')}}金豆</view>
				<view class="update_witch">解锁本集需 {{dataList[k].pay}}金豆</view>
			</view>

			<u-line length="750rpx"></u-line>

			<!-- 自定义套餐充值组件 -->
			<view v-if="vk.vuex.get('$user.userInfo._id')">
				<rechargelist :tv_name="currentInfo.tv_name" :tv_id="currentInfo.tv_id" :recharge="recharge"
					@transfer="transfer" @transfer1="transfer1" @clickRecharge="clickRecharge">
				</rechargelist>
			</view>
		</u-popup>
		<!-- 充值弹窗结束 -->

		<!-- 抖音号弹窗开始 -->
		<u-popup :round="10" mode="center" :show="showgzh">
			<view style="padding: 40rpx;width: 400rpx;height: 267rpx;">
				<view @click="gzhclose" style="margin-left: 90%;">
					<u-icon size="42rpx" name="close"></u-icon>
				</view>
				<view style="align-items: center;display: flex;flex-direction: column;">
					<view style="color: #c43c47;font-size: 40rpx;font-weight: 600;text-align: center;">提示</view>
					<view style="font-size: 32rpx;text-align: center;margin: 40rpx 0;font-weight: 500;">
						{{vk.vuex.get('$app.appinfo.gzgzh_tip')||'关注抖音号，剧情抢先看'}}

					</view>
					<view style="width: 210rpx;margin-top: 30rpx;">
						<button class="buttona" open-type="openAwemeUserProfile" :data-aweme-id="awemeId">
							点击进入
						</button>

					</view>
				</view>
			</view>
		</u-popup>
		<!-- 抖音号弹窗结束 -->
		<!-- 单剧弹窗充值方案 -->
		<u-popup :round="50" mode="center" @close="repurchaseShow = false" :show="repurchaseShow">
			<view class="repurchaseBox">
				<img src="/static/repurchase.png" alt="" class="img1" />
				<div class="repurchaseCenBox">
					<div class="itemblock " :class="{ 'activeItem': activeIndex === index }"
						@click="setActiveIndex(item,index)" v-for="(item,index) in repurchaseData">
						<div class="text-wrapper_1" v-if='item.tehui'>
							<span class="text_1">特惠</span>
						</div>
						<span class="text_2">¥</span>
						<span class="text_3">{{item.recharge_amount/100}}</span>
						<span class="text_7" v-if="item.type==3">{{item.recharge_text}}</span>
						<span class="text_4" v-if="item.type!=3">{{item.recharge_text}}</span>
						<span class="text_5" v-if="item.type!=3">原价{{item.original/100}}元</span>
						<div class="text-wrapper_2">
							<span class="text_6">立即领取</span>
						</div>
					</div>
				</div>
				</div>
			</view>

		</u-popup>
		<!-- 防录屏插件 -->
		<yk-screenRecord></yk-screenRecord>
		<!-- 一部剧播放结束后，推荐其他3部剧 -->

		<view v-if="adviseMore">
			<advisetv></advisetv>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const _ = db.command;
	import rechargelist from '@/components/rechargelist/recharge.vue';

	//防录屏插件
	import ykScreenRecord from '@/components/yk-screenRecord/yk-screenRecord';
	//一部剧播放结束后，推荐其他3部剧
	import advisetv from '@/components/wxlogin/advise-tv.vue'
	export default {
		components: {
			rechargelist,
			ykScreenRecord,
			advisetv
		},
		data() {
			return {
				step: 0,
				adviseMore: false, //默认不展示推荐弹窗，一部剧最后一集播完才提示
				recharge: [], //充值套餐列表
				isShow: false, //视频播放组件是否展示
				show_redicon: false,
				rechargeShow: false, //充值套餐弹窗
				showgzh: false, //公众号弹出框展示和隐藏
				showdingyue: false, //引导用户订阅弹窗展示和隐藏
				currentTab: 0, //弹出框索引
				backtext: "< 返回",
				windowWidth: 0,
				windowHeight: 0, //swiper组件高度
				videoHeight: 0, //视频组件高度
				platform: "",
				deleteHeight: 0,
				dataList: [],
				k: 999,
				current: 999, //和k值一起改，模板的值为0 ，但是为0时进来不会自动播放，所以改成3，也可以改成其他数字
				isChange: true,
				//复购活动数据
				repurchaseData: [{}], //复购弹窗数据
				repurchaseState: false,
				interval: 100, //多少集弹
				repurchaseShow: false,
				activeIndex: 6, //选择的项
				form1: { // 表单请求数据
					provider: "wxpay",
					openid: "",
					total_fee: 1,
					out_trade_no: "",
					subject: "充值金豆",
					body: "得XX金豆",
					type: "recharge"
				},
				datam: '',
				byteAuthorization: '',
				//end
				//popup
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				show: false,
				total: 0,
				all: [],
				list1: [],
				currentInfo: {},
				series_start: 0,
				series_end: 30,
				tvinfo: {
					tv_name: "",
					tv_image: "",
					_id: ""
				}, //包含电视剧名称，封面图和ID
				awemeId: "56038861989",

			}
		},
		watch: {
			async k(k, old_k) {
				console.log("k=", k, "old_k=", old_k);

				this.isShow = false
				//把当前视频信息存到currentInfo
				this.currentInfo = this.dataList[k];
				//判断是否弹窗复购活动弹窗
				if (this.repurchaseState && this.dataList[k].series % this.interval == 0 && !vk.vuex.get(
						'$user.userInfo.request')) {
					this.repurchaseShow = true
				} else {
					this.repurchaseShow = false
				}
				//判断是否需要付费
				let plus_type = vk.vuex.get('$user.userInfo.plus_type');
				console.log("kk00000000000000000000会员", plus_type, this.dataList[k]);
				if (this.dataList[k].pay > 0 && this.dataList[k].had_pay == false && plus_type == 0) {
					//当账户余额小于需支付金额时，提示充值
					if (vk.vuex.get('$user.userInfo.balance') < this.dataList[k].pay) {
						this.isShow = false; //关闭视频播放组件
						this.rechargeShow = true; //弹出充值套餐
						vk.vuex.set('$app.showIndexCoupou', true); //设置首页弹窗开关，true为开启
						return;
					}
					this.paySeries(this.dataList[k], k)
				}


				//当不存在充值方案时，即自动获取方案。如果需要每看一集重新拉取方案，可以把if判断删掉
				if (this.recharge.length == 0) {
					this.getRecgarge()
				}


				//延迟0.5秒，用户观感更顺滑
				setTimeout(() => {
					if (this.currentInfo.pay > 0 && this.currentInfo.had_pay == false && plus_type == 0) {
						this.isShow = false;
						console.log("执行了自动播放为false", this.currentInfo);
					} else {
						console.log("执行了自动播放为true", this.currentInfo);
						this.isShow = true;
					}
				}, 500)


				//检查公众号弹窗和提前三集加载更多视频数据
				this.gzhbox(k)

				//检查下一集的点赞状态
				this.check_like(k)


				// //记录年费会员看剧记录
				// this.vip_history(k)
			}
		},

		async onLoad(option) {
			//判断用户是否登录，未登录则自动登录
			//这里的登录是解决小程序用户直接转发播放页，此时新用户进入小程序不经过首页登录。充值时就会报错
			//延时执行是防止从首页过来时登录代码未执行完
			setTimeout(() => {
				uni.vk.myfn.ttlogin();
			}, 3000)
			this.getRepurchaseData(option.tv_id)
			this.awemeId = vk.vuex.get('$app.dykefu')
			this.copy_onload(option)
			if (vk.vuex.get('$app.currenttv')) {
				this.tvinfo = vk.vuex.get('$app.currenttv')
			} else {
				const tvtemp = await db.collection('a_tv').doc(option.tv_id).get()
				this.tvinfo = tvtemp.result.data[0]
			}
			//计算总集数并分组
			this.computer()
		},
		async onShow() {
			this.recharge = uni.vk.vuex.get('$app.rechargelist');
			console.log("recharge=", this.recharge);

			this.showgzh = false
			await this.zhix()
			setTimeout(() => {
				if (this.dataList.length == 0) {
					this.isShow = false;
					vk.toast('无数据');
					return;
				}
			}, 2000)

			console.log("this.k.pay=", this.dataList[this.k]);
			if (!this.dataList[this.k]) {
				return;
			}

			// 返回首页时,如果本集需付费,且未付费,则弹toast提示。否则就继续播放
			if (this.dataList[this.k].pay > 0 && this.dataList[this.k].had_pay == false) {
				//判断是否需要付费
				//当账户余额小于需支付金额时，提示充值
				if (vk.vuex.get('$user.userInfo.balance') < this.dataList[this.k].pay) {
					this.isShow = false;
					this.rechargeShow = true; //打开充值弹窗
					return;
				}
				//当用户账户余额大于该集所需金额是，开始播放且自动付费。
				this.isShow = true;
				this.paySeries(this.dataList[this.k], this.k)
			} else {
				this.dataList[this.k].state = 'play';
				uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).play()
			}
		},
		onUnload() {
			this.add_history()
		},
		onHide() {
			this.add_history()
		},
		onShareAppMessage() {
			console.log('点击了分享');
			let tv_id = this.tvinfo._id;
			let series = this.currentInfo.series;
			let invite_code = vk.vuex.get('$user.userInfo.my_invite_code');
			let episode_id = this.currentInfo.episode_id;
			let album_id = this.currentInfo.album_id;
			//带上剧ID，集数和个人邀请码转发
			return {
				title: this.tvinfo.tv_name, // 默认为小程序名称
				path: '/pages/index/index?path=player&tv_id=' + tv_id + "&series=" + series + "&invite_code=" +
					invite_code + "&tt_album_id=" + album_id + "&tt_episode_id=" + episode_id,
				imageUrl: this.tvinfo.tv_image // 默认为当前页面的截图
			}
		},
		async onReady() {
			try {
				var res = tt.getSystemInfoSync();
				console.log(`手机型号为 ${res.model}`);
				console.log("获取系统信息", res.windowHeight);
				this.platform = tt.getSystemInfoSync().platform
				var model = tt.getSystemInfoSync().model
				if (this.platform == 'ios' && (model !== 'iPhone6' || model !== 'iPhone6s' || model !== 'iPhone7' ||
						model !==
						'iPhone8')) {
					this.deleteHeight = 50 //有 tabbar的 修改这里可以改变视频高度
				}
				this.windowWidth = tt.getSystemInfoSync().windowWidth;
				this.windowHeight = tt.getSystemInfoSync().windowHeight;
				this.videoHeight = tt.getSystemInfoSync().windowHeight - 70;

			} catch (error) {
				console.log(`获取系统信息失败`);
			}
		},
		methods: {
			async zhix() {
				if (this.step == 1) {
					await uni.vk.myfn.ttlogin();
					setTimeout(() => {
						this.rechargeShow = false;
						// this.isShow = true;
						setTimeout(() => {
							this.click_tvimg(this.currentInfo)
						}, 1500)
					}, 500)
					this.step = 0
				}
				console.log("执行了zhix")
			},
			// 获取复购活动数据
			getRepurchaseData(tv_id) {
				vk.callFunction({
					url: 'client/repurchase/kh/getList',
					data: {
						user_id: vk.vuex.get('$user.userInfo._id'),
						tv_id: tv_id,
						agent_id: vk.vuex.get('$user.userInfo.invite_code'),
					},
					success: (data) => {
						console.log("获取复购活动方案成功", data);
						this.repurchaseState = data.repurchaseState;
						this.repurchaseData = data.repurchaseData;
						this.interval = data.interval || 100
					}
				});
			},
			// 复购活动点击
			setActiveIndex(item, index) {
				this.activeIndex = index
				this.newRecharge(item)
			},
			//.......支付代码开始................................................................................
			//处理充值说明

			async newRecharge(item) {
				uni.showLoading({
					title: "数据校验中..."
				});
				//把当前选中的充值套餐单独存放

				//生成订单号
				this.form1.out_trade_no = uni.vk.pubfn.createOrderNo("NO")

				//退款单号
				this.form1.out_refund_no = uni.vk.pubfn.createOrderNo("ext_")
				//未获取到用户ID则失败
				if (!uni.vk.vuex.get('$user.userInfo._id')) {
					uni.showToast({
						title: "获取信息失败",
						icon: "error"
					})
					return;
				}


				vk.callFunction({
					url: 'client/pay/kh/ttmakeRecharge',
					title: '请求中...',
					data: {
						out_trade_no: this.form1.out_trade_no,
						out_refund_no: this.form1.out_refund_no,
						item,
						tv_id: this.tvinfo._id || "直充",
						tv_name: this.tvinfo.tv_name + "复购充值" || "直充", //记录本次充值来自哪部剧，无来源就是直充
						appid: vk.vuex.get('$app.appid'),
						appname: vk.vuex.get('$app.appname'),

					},
					success: (data) => {
						console.log("创建订单成功", data);
						let add_id = data.add_order.id;
						// this.checkData(item,add_id)
						this.oderlist(item, add_id)
					}
				});
				this.$emit('clickRecharge', 1)
			},

			async oderlist(item, add_id) {
				//从数据库里查找刚添加的订单数据，确保已提交到数据库
				let that = this
				const order_info = await db.collection('a_recharge').doc(add_id).get()
				//找到则发起订单，未找到则提示失败
				if (order_info.result.data.length > 0) {

					//获取签名
					await vk.callFunction({
						url: 'client/pay/kh/paysignature',
						title: '请求中...',
						data: {
							appId: vk.vuex.get('$app.appid'),
							outOrderNo: this.form1.out_trade_no,
							recharge_amount: item.recharge_amount,
							subject: item.subject

						},
						success: (data) => {
							console.log("获取的签名参数", data.byteAuthorization);
							this.byteAuthorization = data.byteAuthorization
							console.log("data参数", data.datam);
							// this.datam=JSON.parse(data.datam)
							this.datam = data.datam
						}
					});
					// JSON.stringify(this.datam)
					console.log("看看服务端传过来的data", this.datam);

					// console.log("看看系统",vk.vuex.get('$app.osName')=='ios');

					// if(vk.vuex.get('$app.osName')=='ios'){

					// }

					await tt.requestOrder({
						header: {
							"Content-Type": "application/json",
						},
						data: JSON.stringify(this.datam),
						byteAuthorization: this.byteAuthorization,
						success: (res) => {
							console.log('拉起收银台成功', res.orderId);

							if (vk.vuex.get('$app.osName') == 'ios') {

								//拉起收银台
								tt.getOrderPayment({
									orderId: res.orderId,
									imId: vk.vuex.get('$app.dykefu'),
									success: async (res) => {
										console.log('支付成功', res);
										uni.showToast({
											title: "充值成功",
											icon: "success"
										})
										//记录充值
										await vk.callFunction({
											url: 'client/repurchase/kh/update',
											title: '请求中...',
											data: {},
											success: (data) => {
												console.log("看看改后的用户数据", data);
												uni.vk.userCenter
													.getCurrentUserInfo({
														success: async (
															data) => {
															console.log(
																"data=",
																data
																.userInfo
															);

															await vk.vuex
																.set(
																	'$user.userInfo',
																	data
																	.userInfo
																)
															await uni.vk
																.myfn
																.updataTime();
															that.transfer(
																data
																.userInfo
																.plus_type
															)
															//触发transfer方法
														}
													});
											}
										});
									},
									fail: (res) => {
										console.log("支付失败", res)
									},

								});

							} else {

								//拉起收银台
								tt.getOrderPayment({
									orderId: res.orderId,
									success: async (res) => {
										console.log('支付成功', res);
										uni.showToast({
											title: "充值成功",
											icon: "success"
										})
										//记录充值
										await vk.callFunction({
											url: 'client/repurchase/kh/update',
											title: '请求中...',
											data: {},
											success: (data) => {
												console.log("看看改后的用户数据", data);
												uni.vk.userCenter
													.getCurrentUserInfo({
														success: async (
															data) => {
															console.log(
																"data=",
																data
																.userInfo
															);

															await vk.vuex
																.set(
																	'$user.userInfo',
																	data
																	.userInfo
																)
															await uni.vk
																.myfn
																.updataTime();
															that.transfer(
																data
																.userInfo
																.plus_type
															)
															//触发transfer方法
														}
													});
											}
										});


									},
									fail: (res) => {
										console.log("支付失败", res)
									},

								});

							}
						},
						fail: (res) => {
							console.log("请求出错", res)
						},
					});

				} else {
					uni.showToast({
						title: "创建订单失败",
						icon: "error"
					})
				}



			},

			//.......支付代码结束................................................................................
			clickRecharge() {
				this.step = 1
				console.log("执行了clickRecharge", this.step);
			},
			transfer(plus_type) {
				console.log("我支付完成后");
				this.show = false
				this.repurchaseShow = false
				this.rechargeShow = false;
				this.activityshow = false;
				// 获取充值方案

				console.log("更新充值方案");
				this.getRecgarge()

				// 返回首页时,如果本集需付费,且未付费,则弹toast提示。否则就继续播放
				if (this.dataList[this.k].pay > 0 && this.dataList[this.k].had_pay == false && plus_type == 0) {
					console.log("我支付完成后1");
					//判断是否需要付费
					//当账户余额小于需支付金额时，提示充值
					if (vk.vuex.get('$user.userInfo.balance') < this.dataList[this.k].pay) {
						console.log("我支付完成后2");
						this.isShow = false;
						this.rechargeShow = true; //打开充值弹窗
						return;
					}

					//当用户账户余额大于该集所需金额是，开始播放且自动付费。
					this.isShow = true;
					this.paySeries(this.dataList[this.k], this.k)
				} else {
					console.log("我支付完成后3");
					this.isShow = true;
					this.dataList[this.k].state = 'play';
					uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).play()
				}

			},
			transfer1(subject) {
				for (let i = 0; i < this.dataList.length; i++) {
					this.dataList[i].pay = 0
				}
				// 获取充值方案
				this.getRecgarge()
				this.getRepurchaseData(this.tvinfo._id)
				console.log("我支付完成后", subject);
				this.rechargeShow = false;
				console.log("我支付完成后", this.rechargeShow);
				this.isShow = true;
				this.show = false;
				this.dataList[this.k].state = 'play';
				uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).play()
			},
			follow_tv() {


				vk.callFunction({
					url: 'client/follow_tv/pub/add',
					data: {
						appid: vk.vuex.get('$app.appid'),
						appname: vk.vuex.get('$app.appname'),
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						nickname: vk.vuex.get('$user.userInfo.nickname') || "匿名用户",
						tv_name: this.tvinfo.tv_name,
						tv_image: this.tvinfo.tv_image,
						tv_id: this.tvinfo._id || "no",
						series: this.currentInfo.series,
						series_id: this.currentInfo._id,
						is_follow: true
					},
					success: (data) => {
						console.log("添加追剧成功");
						this.show_redicon = !this.show_redicon
					}
				});
			},
			getRecgarge() {
				uni.vk.callFunction({
					url: 'client/pay/kh/get_rechargelist',
					// title: '请求中...',
					data: {
						appid: uni.vk.vuex.get('$app.appid')
					},
					success: (data) => {
						console.log("获取模板", data);
						this.recharge = data.recharge;
						if (data.recharge.length > 0) {
							uni.vk.vuex.set('$app.rechargelist', data.recharge)
						}
					}
				});
			},
			copy_onload(option) {
				console.log("option=", option);
				// this.platform = uni.getSystemInfoSync().platform
				// var model = uni.getSystemInfoSync().model
				// if (this.platform == 'ios' && (model !== 'iPhone6' || model !== 'iPhone6s' || model !== 'iPhone7' ||
				// 		model !==
				// 		'iPhone8')) {
				// 	this.deleteHeight = 50 //有 tabbar的 修改这里可以改变视频高度
				// }
				// this.windowWidth = uni.getSystemInfoSync().windowWidth;
				// this.windowHeight = uni.getSystemInfoSync().windowHeight;
				// this.videoHeight = uni.getSystemInfoSync().windowHeight - 70;
				vk.callFunction({
					url: 'client/video/pub/all_series',
					title: "加载中...",
					data: {
						series: option.series || "", //如果参数里有集数，则传集数，没集数默认空
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						tv_id: option.tv_id,
						plus_type: vk.vuex.get('$user.userInfo.plus_type') || 0
					},
					success: (data) => {
						//为了避免0集的问题，当jump_serie为空或0是，赋值为1
						if (data.jump_serie * 1 == 0) {
							data.jump_serie = 1
						}
						console.log("处理后的数据", data);
						this.dataList = data.series
						console.log("########################", this.dataList);
						for (var i = 0; i < data.series.length; i++) {
							//逐一判断当前数据列表里的集数和options里传过来的集数，相等时取i值，就是历史播放记录
							if (data.series[i].series == data.jump_serie * 1) {
								this.current = i
								this.k = i
								break;
							}
						}
					}
				});
			},
			loadMoreSerie(currentSerie) {
				//视频数量不足时，及时加载更多视频数据
				var that = this;
				vk.callFunction({
					url: 'client/video/pub/start_end_series',
					data: {
						start: currentSerie + 1,
						end: currentSerie + 30,
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						tv_id: this.tvinfo._id,
						plus_type: vk.vuex.get('$user.userInfo.plus_type') || 0
					},
					success: (data) => {
						console.log("loadMoreSerie数据", data);
						that.dataList = that.dataList.concat(data.series)
					}
				});
			},
			//点击选集图标
			xuanji() {
				this.get_series_info(1, 30)
				this.show = true
			},

			//点击弹出框的分集tab
			click(item) {
				console.log('clickitem', item);
				this.currentTab = 0;
				this.series_start = item.start;
				this.series_end = item.end;
				this.get_series_info(item.start, item.end)
			},

			//点击选集跳转
			check_series(item, index) {
				var that = this;
				console.log("check_series_item=", item);
				console.log("check_series_index=", index);
				// 判断金豆是否不足,不足的话直接提示去充值
				// this.current = index;
				// this.k = index;

				let plus_type = vk.vuex.get('$user.userInfo.plus_type');
				if (vk.vuex.get('$user.userInfo.balance') < item.pay && item.had_pay == false && plus_type == 0) {
					this.current = index;
					that.dataList = that.all;
					this.k = index; //解决弹窗选集时，无法正确展示本集需要多少金豆的问题
					this.rechargeShow = true; //打开充值弹窗
					return;
				}

				if (item.pay > 0 && item.had_pay == false && plus_type == 0) {
					uni.showModal({
						title: "账户金豆余额:" + vk.vuex.get('$user.userInfo.balance'),
						content: "该集为付费内容，是否花" + item.pay + "金豆购买",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								// that.paySeries(item, index)
								that.dataList = that.all;
								that.dataList[index].had_pay == true
								that.current = index;
								that.k = index;
								that.show = false


							} else if (res.cancel) {
								//点取消，设置一下showIndexCoupou，返回首页后会弹窗优惠
								vk.vuex.set('$app.showIndexCoupou', true)
								console.log('用户点击取消');
							}
						}
					})
					return;
				} else {
					that.dataList = that.all;
					this.current = index;
					this.k = index;
					this.show = false
					//如果是数据列表里最后一项，就继续加载数据
					if (index == this.dataList.length - 1) {
						let currentSerie = this.dataList[index].series
						//继续加载更多
						this.loadMoreSerie(currentSerie)
					}
				}


			},
			paySeries(item, index) {
				if (item.pay == 0) {
					return;
				}
				var that = this;
				vk.callFunction({
					url: 'client/pay/kh/paySeries',
					data: {
						tv_id: this.tvinfo._id,
						tv_name: this.tvinfo.tv_name,
						series: item.series,
						pay_amount: item.pay,
						series_id: item._id
					},
					complete: (res) => {
						if (res.result.money == -1) {
							that.rechargeShow = true; //打开充值弹窗
							return;
						}
						let userBalance = vk.vuex.get('$user.userInfo.balance')
						//修改前端用户金豆数量
						vk.vuex.set('$user.userInfo.balance', userBalance * 1 - item.pay * 1)
						// vk.toast('自动购买成功！该集已解锁');
						//遍历dataList数组，找到付费的集数，并解锁，防止用户来回切换标签页后导致未解锁
						for (var i = 0; i < that.dataList.length; i++) {
							if (that.dataList[i]._id == item._id) {
								that.dataList[i].had_pay = true
							}
						}
					},
				});
			},



			//计算一共有多少组数据
			async computer() {
				const tv_total = await db.collection('a_tv_series').where({
					tv_id: this.tvinfo._id
				}).count()
				this.total = tv_total.result.total
				//当总集数不超过30集，直接1到总集数
				if (this.total < 31) {
					this.list1.push({
						name: "1-" + this.total,
						start: 1,
						end: this.total
					})
					this.get_series_info(1, this.total)
				} else {
					let b = this.total / 30;
					let intb = Math.ceil(b)
					// console.log("最后一部分的集数=", intb); //向上取整数
					for (var i = 0; i < intb; i++) {
						let start = i * 30 + 1;
						let end = i * 30 + 30;
						if (end > this.total) {
							end = this.total
						}
						this.list1.push({
							name: start + "-" + end,
							start: start,
							end: end
						})
					}
				}
			},
			//获取每组数据的具体详情
			async get_series_info(start, end) {
				console.log(start, "-", end);
				uni.showLoading({
					title: "加载中..."
				})
				var that = this;
				// that.all = []
				if (!start) {
					start = 1
				}
				if (!end) {
					end = 30
				}

				vk.callFunction({
					url: 'client/video/pub/start_end_series',
					data: {
						start: start,
						end: end,
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						tv_id: this.tvinfo._id,
						plus_type: vk.vuex.get('$user.userInfo.plus_type') || 0
					},
					success: (data) => {
						console.log("player页面处理后的数据", data);
						that.all = data.series
						uni.hideLoading()
					}
				});
			},
			error(e) {
				console.log("e=======", e);
			},
			getsource(e) {
				const a = tt.canIUse('video-player.bindgetsource')
				console.log("a================", e);

			},
			ended() {
				console.log("5555555");
				if (this.k == this.dataList.length - 1) {
					uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).seek(0)
					uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).pause()
					this.adviseMore = true; //全部播放完后，推荐更多视频
				} else {
					this.current = this.k + 1
				}
			},



			//点击播放&&暂停
			play() {
				//记录看剧记录
				this.vip_history()
				console.log("开始播放");
			},

			//当视频暂停时，会展示封面图，点击封面图触发此事件
			async click_tvimg(item) {
				console.log("点击了封面图");
				let plus_type = vk.vuex.get('$user.userInfo.plus_type');
				// 判断金豆是否不足,不足的话直接提示去充值
				if (vk.vuex.get('$user.userInfo.balance') < item.pay && item.had_pay == false && plus_type == 0) {
					this.rechargeShow = true; //打开充值弹窗
					return;
				}

				//账户余额大于当前集需要支付的金豆数，且当前集未支付，且当前需支付的金豆数大于0
				if (vk.vuex.get('$user.userInfo.balance') > item.pay && item.had_pay == false && item.pay > 0 &&
					plus_type == 0) {
					this.paySeries(this.dataList[this.k], this.k); //调用支付函数
					this.isShow = true; //展示视频播放组件
					return;
				}
				this.isShow = true; //展示视频播放组件
			},


			change(event) {
				this.k = event.detail.current;
				//current一定要改，否则会出现选集黑屏的问题
				this.current = event.detail.current
			},

			//swiper动画结束时会触发animationfinish事件
			animationfinish(event) {
				//这里进行判断，如果是最后一个视频就加载视频进入列表
				if (this.k == this.dataList.length - 1) {
					// this.GETNEW()
				}
			},

			//用户点赞操作
			cLike(like_state) {
				//like_state代表是点赞还是取消点赞，点赞是false,取消是true
				console.log("like_state=", like_state);
				this.dataList[this.k].like = !this.dataList[this.k].like
				const video = this.dataList[this.k];
				if (like_state) {
					video.like_num = video.like_num * 1 - 1
				} else {
					video.like_num = video.like_num * 1 + 1
				}
				//操作数据库，点赞则新增一条点赞记录，取消点赞则删除记录
				vk.callFunction({
					url: 'client/video/pub/click_like',
					data: {
						like_state: like_state,
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						nickname: vk.vuex.get('$user.userInfo.nickname') || "匿名用户",
						tv_name: this.tvinfo.tv_name,
						tv_image: this.tvinfo.tv_image,
						tv_id: this.tvinfo._id || "no",
						series: this.currentInfo.series,
						series_id: this.currentInfo._id,
					},
					success: (data) => {
						console.log("云函数执行完成");
					}
				});
			},

			//当页面隐藏或卸载时，记下观看记录
			async add_history() {
				uni.setStorageSync('seriesList', '')
				if (!vk.vuex.get('$user.userInfo._id')) {
					return;
				}
				vk.callFunction({
					url: 'client/history/pub/add',
					data: {
						user_id: vk.vuex.get('$user.userInfo._id'),
						nickname: vk.vuex.get('$user.userInfo.nickname') || '匿名用户',
						tfid: vk.vuex.get('$user.userInfo.tfid') || 0,
						invite_code: vk.vuex.get('$user.userInfo.invite_code') || 0,
						middleman_id: vk.vuex.get('$user.userInfo.middleman_id') || 0,
						tfid: vk.vuex.get('$user.userInfo.tfid'),
						tv_name: this.tvinfo.tv_name,
						tv_id: this.tvinfo._id,
						tv_image: this.tvinfo.tv_image,
						series: this.currentInfo.series,
						series_id: this.currentInfo._id,
						is_follow: false,
					},
					success: (data) => {
						console.log("添加历史成功");
					}
				});
			},

			//检查下一集的点赞状态
			async check_like(k) {
				vk.callFunction({
					url: 'client/video/pub/check_LikeAndPay',
					data: {
						user_id: vk.vuex.get('$user.userInfo._id') || "no",
						series_id: this.dataList[this.k]._id,
						nextseries_id: this.dataList[k + 1]._id,
						k: k
					},
					success: (data) => {
						if (data.like_k) {
							this.dataList[k].like = true
						}
						if (data.next_like_k) {
							this.dataList[k + 1].like = true
						}
					}
				});
			},

			//检查公众号弹窗
			async gzhbox(k) {
				//引导关注公众号弹窗
				let gzhstart = this.tvinfo.gzhbox_start * 1 - 1;
				let gzhend = this.tvinfo.gzhbox_end * 1;
				if (this.dataList[k].series > gzhstart && this.dataList[k].series < gzhend) {
					console.log("启动公众号弹窗");
					//存储在vuex里的变量，记录了用户是否已经打开过公众号链接
					//如果已打开过，hide_gzhbox为true,则再次看剧时不弹公众号窗口
					if (vk.vuex.get('hide_gzhbox') == false) {
						this.showgzh = true
						return;
					}
				}


				//提前三集加载更多视频数据
				if (k > this.dataList.length - 4) {
					console.log("播放到倒数第三集了", this.dataList[this.dataList.length - 1].series);
					let currentSerie = this.dataList[this.dataList.length - 1].series
					//如果当前不是最后一集，就继续加载更多
					if (this.total > currentSerie) {
						this.loadMoreSerie(currentSerie)
					}
				}
			},

			//记录用户的看剧记录
			async vip_history() {
				vk.callFunction({
					url: 'client/history/kh/vip_history',
					// title: '请求中...',
					data: {
						appid: vk.vuex.get('$app.appid'),
						appname: vk.vuex.get('$app.appname'),
						tv_name: this.tvinfo.tv_name,
						tv_id: this.tvinfo._id,
						tv_image: this.tvinfo.tv_image,
						series: this.currentInfo.series,
						series_id: this.currentInfo._id,
					},
					success: (data) => {
						console.log("记录用户看剧记录");
					}
				});
			},

			open() {
				console.log('选集框已打开');
			},
			close() {
				this.show = false
				this.showgzh = false
			},
			rechargeopen() {
				console.log("充值弹窗开启");
			},
			gzhclose() {
				//关闭公众号弹窗
				this.showgzh = false
			},
			closedingyue() {

				// this.showdingyue = false;

			},

			upper: function(e) {

			},
			lower: function(e) {

			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			jump(url) {
				//用户点击进入公众号以后，下次就不再展示
				vk.vuex.set('hide_gzhbox', true)
				uni.navigateTo({
					url: url
				})
			},
			//视频加载进度
			progress(e) {
				// console.log("当前视频加载进度=", e.detail.buffered);
			},
			progress2(e) {
				// console.log("预加载视频进度=", e.detail.buffered);
			},
		}
	}
</script>


<style lang="scss">
	page {
		background-color: #000000;
	}

	.buttona::after {
		border: none;
	}

	.buttona {
		height: 38px;
		line-height: 35px;
		border-radius: 26px 26px;
		background-color: #f56c6c;
	}

	.aaaaaimage {
		/* height: 100% !important; */
		/* width: 100% !important; */
		/* height: 100%; */
		width: 100%;
		height: 1300rpx;
		object-fit: cover;
	}

	/* //选集文字的样式 */
	.xuanjiStyle {
		color: #FFFFFF;
		/* margin-top: 5px; */
		font-size: 14px;
		font-weight: bold;
		/* text-align: center; */
	}

	.userInfo {
		z-index: 999;
		position: absolute;
		bottom: 160px;
		right: 10px;
		display: flex;
		flex-direction: column;
	}

	.likeNumActive {
		color: red;
	}

	.content {
		width: 720rpx;
		z-index: 99;
		position: absolute;
		bottom: 8px;
		/* justify-content: center; */
		padding: 15rpx;
		flex-direction: column;
		justify-content: flex-start;
		color: #ffffff;
	}

	.userName {
		font-size: 30rpx;
		color: #ffffff;
		/* margin-top: 80rpx; */
	}

	.words {
		margin-top: 10rpx;
		font-size: 30rpx;
		color: #ffffff;
	}

	/* //popup */
	.tv_name {
		font-size: 32rpx;
		font-weight: 600;
		margin: 20rpx 0 10rpx 20rpx;
	}

	.update_witch {
		font-size: 30rpx;
		margin: 0 0 20rpx 20rpx;
	}

	.scroll-Y {
		height: 900rpx;
	}


	.tv_image {
		/* position: relative; */
		width: 230rpx;
		height: 364rpx;
		border-radius: 10rpx;
	}

	.series {
		/* position: absolute; */
		color: #fff;
		background-color: black;
		opacity: 0.9;
		width: 230rpx;
		height: 50rpx;
		text-align: center;
		border-radius: 0 0 10rpx 10rpx;
		margin-top: -60rpx;
		background: rgba(0, 0, 0, 0.7);
	}

	.lock {
		width: 80rpx;
		height: 80rpx;
		position: absolute;
		margin-top: 120rpx;
		margin-left: 75rpx;
	}

	.lock_bg {
		background: rgba(0, 0, 0, 0.4);
		height: 314rpx;
		width: 230rpx;
		border-radius: 10rpx 10rpx 0 0;
		position: absolute;
		margin-top: -364rpx;
	}

	.backstyle {
		color: #FFFFFF;
		position: fixed;
		/* background-color: aqua; */
		margin-top: 80rpx;
		margin-left: 30rpx;
		z-index: 9999999;
		height: 60rpx;
		width: 150rpx;
	}



	.repurchaseBox {
		position: relative;
		width: 662rpx;
		height: 821rpx;
		background: linear-gradient(180deg, #fffffe 0%, #fefcf6 100%);
		border-radius: 50rpx;
	}

	.repurchaseCenBox {
		margin-top: 5rpx;
		position: relative;
	}

	.img1 {
		width: 662rpx;
		height: 196rpx;
		// background: linear-gradient(115deg, #FFE8D5 0%, #FFD4B6 50%, #FFE1CE 100%);
		// border-radius: 50rpx 50rpx 100rpx 100rpx;
	}

	.itemblock {
		position: relative;
		width: 614rpx;
		height: 132rpx;
		background: #FFF7E9;
		border: 2rpx solid #FDE7D8;
		margin: 10rpx 24rpx;
		border-radius: 18rpx;

	}

	.text-wrapper_1 {
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 0%;
		left: 0%;
		width: 80rpx;
		height: 40rpx;
		background: linear-gradient(90deg, #FF9748 0%, #FF5E22 100%);
		border-radius: 12rpx 0rpx 24rpx 0rpx;
	}

	.text_1 {
		width: 40rpx;
		height: 28rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 20rpx;
		color: #FFFFFF;
		line-height: 28rpx;
		text-align: right;
		font-style: normal;
		font-weight: bold
	}

	.activeItem {
		background: linear-gradient(90deg, #FEE8BF 0%, #FFD07F 100%);
	}

	.text_2 {
		position: absolute;
		top: 40rpx;
		left: 69rpx;
		width: 15rpx;
		height: 33rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 600;
		font-size: 24rpx;
		color: #D1281B;
		line-height: 33rpx;
		text-align: right;
		font-style: normal;
		font-weight: bold
	}

	.text_3 {
		position: absolute;
		top: 32rpx;
		left: 87rpx;
		width: 84rpx;
		height: 67rpx;
		font-family: Arial, Arial;
		font-weight: normal;
		font-size: 60rpx;
		color: #D1281B;
		line-height: 69rpx;
		text-align: left;
		font-style: normal;
		font-weight: bold
	}

	.text_4 {
		position: absolute;
		top: 26rpx;
		left: 214rpx;
		width: 250rpx;
		height: 42rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #000000;
		line-height: 42rpx;
		text-align: left;
		font-style: normal;
		font-weight: bold
	}

	.text_7 {
		position: absolute;
		top: 44rpx;
		left: 214rpx;
		width: 230rpx;
		height: 42rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #000000;
		line-height: 42rpx;
		text-align: left;
		font-style: normal;
		font-weight: bold
	}

	.text_5 {
		position: absolute;
		top: 76rpx;
		left: 216rpx;
		width: 120rpx;
		height: 30rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 22rpx;
		color: rgba(0, 0, 0, 0.4);
		line-height: 30rpx;
		text-align: left;
		font-style: normal;
		text-decoration: line-through;
	}

	.text_6 {
		width: 96rpx;
		height: 33rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 24rpx;
		color: #FFFFFF;
		line-height: 33rpx;
		text-align: right;
		font-style: normal;
	}

	.text-wrapper_2 {
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 37rpx;
		left: 444rpx;
		width: 150rpx;
		height: 58rpx;
		background: linear-gradient(90deg, #FD7C3A 0%, #FD2222 100%);
		border-radius: 33rpx;
	}
</style>